package com.atelier.plugin.projectWizard;

import com.atelier.plugin.projectWizard.util.MavenArchetypeGenerator;
import com.atelier.plugin.service.SettingsStorageService;
import com.intellij.openapi.components.ProjectComponent;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class HywayApplication implements ProjectComponent {
    public static String wrapperDir;
    public static String repositoryDir;

    public static String tempDir;
    public static String tmp;
    @Override
    public void disposeComponent() {
        System.out.println("组件销毁~~~~~");

        ProjectComponent.super.disposeComponent();
    }

    @Override
    public void projectOpened() {
        System.out.println("项目打开阶段");
        ProjectComponent.super.projectOpened();
    }

    @Override
    public void initComponent() {
        // 获取 Maven Wrapper 目录和 Maven 仓库目录的临时路径
        try {
            SettingsStorageService.getSettingsStorage().resetDefaultVal();
            File file = new File(System.getProperty("java.io.tmpdir"));
            wrapperDir = createTempDirectory("apache-maven-3.8.8");
            repositoryDir = createTempDirectory("repository");
            tempDir=createTempDirectory("archetype");
            tmp=file.getPath();
            System.out.println("tmp"+tmp);
            System.out.println(wrapperDir);
            System.out.println(repositoryDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 复制 模板 文件夹
        try {
            copyResourceDirectory("/archetype.zip", tempDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 复制 Maven Wrapper 文件夹
        try {
            copyResourceDirectory("/apache-maven-3.8.8.zip", wrapperDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 复制 Maven 仓库文件夹
        try {
            copyResourceDirectory("/repository.zip", repositoryDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        MavenArchetypeGenerator.generateMavenArchetype(tempDir);
        System.out.println(wrapperDir);
        System.out.println(repositoryDir);
        System.out.println("插件初始化中~~~~~~~");
    }

    private static String createTempDirectory(String directoryName) throws IOException {
         File file = new File(System.getProperty("java.io.tmpdir"));
        System.out.println("file"+file);
        File tempDir = new File(System.getProperty("java.io.tmpdir"), directoryName);
        System.out.println("tempDir"+tempDir);
        if (tempDir.exists() && tempDir.isDirectory()) {
            FileUtils.deleteDirectory(tempDir);
        }
        tempDir.mkdirs();
        System.out.println("tempDir.getAbsolutePath()"+tempDir.getAbsolutePath());
        return tempDir.getAbsolutePath();
    }

    private static void copyResourceDirectory(String resourcePath, String destinationPath) throws IOException {
        InputStream inputStream = HywayApplication.class.getResourceAsStream(resourcePath);
        if (inputStream == null) {
            throw new IOException("Failed to load resource: " + resourcePath);
        }

        // 创建临时目录
        File tempDir = new File(System.getProperty("java.io.tmpdir"));
        File destDir = new File(destinationPath);
        destDir.mkdirs();

        // 解压zip文件
        File zipFile = new File(tempDir, getFileNameFromResourcePath(resourcePath));
        System.out.println(destDir);
        File extractDir = destDir;
        if (extractDir.exists()) {
            FileUtils.deleteDirectory(extractDir);  // 删除已存在的解压目录
        }

        // 将zip文件复制到临时目录
        try (OutputStream outputStream = new FileOutputStream(zipFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        }

        inputStream.close();

        // 解压zip文件
        unzip(zipFile.toPath(), extractDir.toPath());

        // 删除临时zip文件
        zipFile.delete();
    }

    private static void unzip(Path zipFilePath, Path extractDirPath) throws IOException {
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath.toFile()))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                String entryName = entry.getName();
                Path entryPath = extractDirPath.resolve(entryName);
                if (entry.isDirectory()) {
                    Files.createDirectories(entryPath);
                } else {
                    Files.createDirectories(entryPath.getParent());
                    Files.copy(zipInputStream, entryPath, StandardCopyOption.REPLACE_EXISTING);
                }
                zipInputStream.closeEntry();
            }
        }
    }

    private static String getFileNameFromResourcePath(String resourcePath) {
        return resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
    }

    private static String getDirectoryNameFromZipFile(String zipFileName) {
        return zipFileName.substring(0, zipFileName.lastIndexOf("."));
    }
}
// 其他方法和组件生命周期方法（如disposeComponent）省略

